<template>
  <XtxBread>
    <XtxBreadItem to="/">首页</XtxBreadItem>
    <XtxBreadItem v-if="category.top" :to='`/category/${category.top.id}`' > {{ category.top.name }}</XtxBreadItem>
    <Transition name="fade-right" mode="out-in">
      <XtxBreadItem :key="category.sub.id" v-if="category.sub">{{ category.sub.name }}</XtxBreadItem>
    </Transition>
  </XtxBread>
</template>
<script>
import { computed } from "vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";

export default {
  setup(props) {
    /**
           通过属性从vuex获取顶级和二级类目
           数据对象 {top:{id,name}, sub:{id,name}}
         */
    const route = useRoute();
    const store = useStore();

    const category = computed(() => {
      const cate = {};
      store.state.category.list.forEach((top) => {
        if (top.children) {
          // 有子集类目才使用find
          const sub = top.children.find((v) => v.id === route.params.id);
          if (sub) {
            cate.top = { id: top.id, name: top.name };
            cate.sub = { id: sub.id, name: sub.name };
          }
        }
      });
      return cate;
    });

    return { category };
  },
};
</script>